package com.example.bootdemo5.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.bootdemo5.common.CommonResult;
import com.example.bootdemo5.pojo.Employee;
import com.example.bootdemo5.service.IEmployeeService;
import com.example.bootdemo5.util.JwtUtil;
import com.example.bootdemo5.util.RedisServiceUtil;
import com.example.bootdemo5.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "身份认证接口", tags="身份认证接口")
@RestController
public class AuthsController {

    @Autowired
    IEmployeeService  employeeService;
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RedisServiceUtil  redisServiceUtil;

    @Value("${my.enableRedisToken}")
    Boolean   enableRedisToken;

    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public CommonResult  login(@RequestBody UserVo  userVo){
        QueryWrapper<Employee>  wrapper  =new QueryWrapper(); //查询包裹体
        wrapper.eq("username",userVo.getUsername()).eq("password",userVo.getPassword());
        Employee employee=  employeeService.getOne(wrapper);
        //生成TOKEN
        String token =jwtUtil.generateToken(employee.getUsername());
        if(enableRedisToken){
            redisServiceUtil.hset("token_valid_list",token,employee);
        }
        return employee==null? CommonResult.FAILURE("用户名或者密码错误"):CommonResult.SUCCESS("登录成功",token);

    }


    /**
     * Employee::getUsername  方法引用   lambda 表达式 对箭头函数的进一步简写  java8的新特性
     * @param userVo
     * @return
     */
    @ApiOperation("用户登录接口2")
    @PostMapping("/login2")
    public CommonResult  login2(@RequestBody UserVo  userVo){
        LambdaQueryWrapper<Employee> wrapper=Wrappers.lambdaQuery();
        wrapper.eq(Employee::getUsername,userVo.getUsername()).eq(Employee::getPassword,userVo.getPassword());
        Employee employee  = employeeService.getOne(wrapper);
        return employee==null?CommonResult.FAILURE("用户名或者密码错误"):CommonResult.SUCCESS("登录成功",employee);

    }




}








